use std::rc::Rc;
use chrono::Datelike;
use slint::{Model, ModelRc, SharedString, SharedVector};
use serde::{Deserialize, Serialize};
use crate::data::get_month_days;

#[derive(Clone)]
struct DayItem {
    day: String,
    color: String,
}

fn convert_to_slint_model(data: Vec<Vec<DayItem>>) -> ModelRc<ModelRc<(SharedString, SharedString)>> {
    let mut inner_model = SharedVector::default();
    for inner_vec in data {
        let mut dict = SharedVector::with_capacity(16);
        for item in inner_vec {
            dict.push((SharedString::from(item.color), SharedString::from(item.day)));
        }
        inner_model.push(ModelRc::from(dict.as_slice()));
    }
    ModelRc::from(inner_model.as_slice())
}

mod data;
slint::include_modules!();
fn main() -> Result<(), slint::PlatformError> {
    let main = Rc::new(MainWindow::new().unwrap());
    let main_window = main.window();
    main_window.set_fullscreen(true);
    // 设置模型数据
    let now = chrono::Local::now();
    let mut current_year = now.year();
    let mut current_month = now.month();
    let init_calender = |main: &Rc<MainWindow>, current_year: i32, current_month: u32| {
        let day_items = get_month_days(current_year, current_month);
        let slint_model = convert_to_slint_model(day_items);
        main.set_day_items(slint_model);
    };
    init_calender(&main, current_year.clone(), current_month.clone());
    main.clone().on_clicked(|day_item| {
        println!("{}", day_item);
    });
    let rc_main2 = main.clone();
    main.clone().on_preMonth(move || {
        if (current_month == 1) {
            current_month = 12;
            current_year -= 1;
        } else {
            current_month -= 1;
        }
        init_calender(&rc_main2, current_year.clone(), current_month.clone());
    });
    let rc_main = main.clone();
    main.clone().on_nextMonth(move || {
        if (current_month == 12) {
            current_month = 1;
            current_year += 1;
        } else {
            current_month += 1;
        }
        init_calender(&rc_main, current_year.clone(), current_month.clone());
    });

    main.run()?;
    Ok(())
}